<template>
	<view class="activity-detail">
		<!-- 顶部导航
		<view class="nav-bar">
			<view class="back-btn" @click="goBack">
				<uni-icons type="left" size="20" color="#333"></uni-icons>
			</view>
			<view class="nav-title">活动详情</view>
		</view>
		 -->
		<!-- 活动信息卡片 -->
		<view class="activity-card" v-if="activityDetail">
			<view class="activity-cover">
				<image :src="getImageUrl(activityDetail.cover)" mode="aspectFill"></image>
				<view class="status-tag" :class="getStatusClass(activityDetail)">
					{{ getStatusText(activityDetail) }}
				</view>
			</view>
			
			<view class="activity-info">
				<view class="activity-title">{{ activityDetail.title }}</view>
				
				<view class="info-item">
					<uni-icons type="calendar" size="16" color="#666"></uni-icons>
					<text>{{ formatDate(activityDetail.startTime) }} ~ {{ formatDate(activityDetail.endTime, true) }}</text>
				</view>
				
				<view class="info-item">
					<uni-icons type="location" size="16" color="#666"></uni-icons>
					<text>{{ activityDetail.location || activityDetail.address || '暂无地点信息' }}</text>
				</view>
				
				<view class="info-item">
					<uni-icons type="person" size="16" color="#666"></uni-icons>
					<text>{{ getCurrentParticipants() }}/{{ getMaxParticipants() }}人</text>
				</view>
				
				<!-- 参与进度 -->
				<view class="progress-box">
					<progress 
						:percent="getParticipantsPercent()" 
						stroke-width="4" 
						activeColor="#2979ff" 
						backgroundColor="#eee"
					></progress>
				</view>
			</view>
		</view>
		
		<!-- 活动详情内容 -->
		<view class="content-card" v-if="activityDetail">
			<view class="card-title">
				<text>活动详情</text>
			</view>
			<view class="activity-content rich-text-container">
				<rich-text :nodes="getContentHtml()"></rich-text>
			</view>
		</view>
		
		<!--  参与人员 -->
		<view class="content-card" v-if="participantList.length > 0">
			<view class="card-title">
				<text>参与人员</text>
				<text class="title-count">({{ participantList.length }}人)</text>
			</view>
			<view class="participants-list">
				<view class="participant-item" v-for="(item, index) in participantList" :key="index">
					<text class="nickname">{{ item.nickname || item.username || '用户' + item.userId }}</text>
					<text class="join-time">{{ formatDate(item.joinTime || item.createTime, true) }}报名</text>
				</view>
			</view>
		</view> -
		
		<!-- 加载中 -->
		<view class="loading-container" v-if="loading">
			<uni-load-more status="loading" :contentText="loadMoreText"></uni-load-more>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="bottom-bar" v-if="activityDetail">
			<button 
				class="action-btn" 
				:class="[canJoin ? 'btn-primary' : 'btn-disabled']"
				:disabled="!canJoin"
				@click="handleActionClick"
			>
				{{ actionButtonText }}
			</button>
		</view>
	</view>
</template>

<script>
import { getActivityDetail, getActivityParticipants, signupActivity, cancelSignup } from '@/api/activity.js';
import {getImageUrl} from '@/utils/image.js';
export default {
	data() {
		return {
			id: null,
			loading: true,
			activityDetail: null,
			participantList: [],
			hasJoined: false,
			dataChanged: false,
			loadMoreText: {
				contentdown: '上拉加载更多',
				contentrefresh: '加载中...',
				contentnomore: '没有更多了'
			}
		};
	},
	computed: {
		// 是否可以参与活动
		canJoin() {
			if (!this.activityDetail) return false;
			
			// 活动未开始或已结束，不可参与
			if (this.activityDetail.status === 0 || this.activityDetail.status === 2) return false;
			
			// 人数已满且未报名，不可参与
			if (this.getCurrentParticipants() >= this.getMaxParticipants() && !this.hasJoined) return false;
			
			return true;
		},
		
		// 按钮文本
		actionButtonText() {
			if (!this.activityDetail) return '';
			
			// 根据活动状态决定按钮显示文本
			if (this.activityDetail.status === 0) {
				return '活动未开始';
			} else if (this.activityDetail.status === 2) {
				return '活动已结束';
			}
			
			// 人数已满且未报名
			if (this.getCurrentParticipants() >= this.getMaxParticipants() && !this.hasJoined) {
				return '名额已满';
			}
			
			// 已报名
			if (this.hasJoined) {
				return '取消预约';
			}
			
			// 默认
			return '立即预约';
		}
	},
	onLoad(options) {
		console.log('接收到的参数:', options);
		if (options.id) {
			this.id = options.id;
			this.loadActivityDetail();
			this.loadParticipants();
		} else {
			uni.showToast({
				title: '参数错误',
				icon: 'none'
			});
			setTimeout(() => {
				this.goBack();
			}, 1500);
		}
	},
	// 页面卸载时确保标记已设置
	onUnload() {
		// 如果用户进行了预约或取消预约操作，确保设置刷新标记
		if (this.dataChanged) {
			getApp().globalData = getApp().globalData || {};
			getApp().globalData.activityListNeedRefresh = true;
		}
	},
	methods: {
		// 获取封面图片
		getImageUrl,

		
		// 获取当前参与人数
		getCurrentParticipants() {
			if (!this.activityDetail) return 0;
			return this.activityDetail.currentParticipants || this.activityDetail.participantsCount || 0;
		},
		
		// 获取最大参与人数
		getMaxParticipants() {
			if (!this.activityDetail) return 0;
			return this.activityDetail.maxParticipants || this.activityDetail.maxCount || 50;
		},
		
		// 获取参与进度百分比
		getParticipantsPercent() {
			const current = this.getCurrentParticipants();
			const max = this.getMaxParticipants();
			if (max <= 0) return 0;
			return (current / max) * 100;
		},
		
		// 获取内容HTML
		getContentHtml() {
			if (!this.activityDetail) return '';
			return this.activityDetail.content || 
				   this.activityDetail.description || 
				   this.activityDetail.detail || 
				   '<p>暂无详细内容</p>';
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		
		// 加载活动详情
		async loadActivityDetail() {
			this.loading = true;
			try {
				console.log('加载活动详情，ID:', this.id);
				const res = await getActivityDetail(this.id);
				console.log('活动详情结果:', res);
				
				if (res.code === 200) {
					// 新的API响应结构中，活动详情在res.data.activity
					this.activityDetail = res.data.activity || res.data;
					console.log('处理后的活动详情:', this.activityDetail);
					
					// 直接从响应中获取是否已报名
					if (res.data.hasOwnProperty('isSignedUp')) {
						this.hasJoined = res.data.isSignedUp;
						console.log('用户报名状态(来自API):', this.hasJoined);
					} else {
						// 如果API没有提供报名状态，则从参与人员列表检查
						this.checkUserJoinStatus();
					}
				} else {
					uni.showToast({
						title: res.message || '加载失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('加载活动详情失败', error);
				uni.showToast({
					title: '网络异常，请稍后重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 加载参与人员列表
		async loadParticipants() {
			try {
				console.log('加载参与人员，活动ID:', this.id);
				const res = await getActivityParticipants(this.id);
				console.log('参与人员结果:', res);
				
				if (res.code === 200) {
					this.participantList = res.data || [];
					
					// 如果活动详情接口没有返回预约状态，再从参与者列表确认
					if (res.data.hasOwnProperty('isSignedUp') === false) {
						this.checkUserJoinStatus();
					}
				}
			} catch (error) {
				console.error('加载参与人员失败', error);
			}
		},
		
		// 检查用户是否已报名
		checkUserJoinStatus() {
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo || !userInfo.id) {
				this.hasJoined = false;
				return;
			}
			
			// 从参与人员列表中检查当前用户是否已报名
			if (this.participantList.length > 0) {
				this.hasJoined = this.participantList.some(item => 
					item.userId === userInfo.id || item.id === userInfo.id
				);
				console.log('用户报名状态(通过参与列表验证):', this.hasJoined);
			}
		},
		
		// 格式化日期
		formatDate(dateStr, timeOnly = false) {
			if (!dateStr) return '';
			const date = new Date(dateStr);
			
			if (timeOnly) {
				return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			}
			
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
		},
		
		// 获取活动状态样式
		getStatusClass(activity) {
			// 根据后端返回的status字段判断状态
			if (activity.status === 0) {
				return 'status-upcoming'; // 未开始
			} else if (activity.status === 1) {
				return 'status-ongoing';  // 报名中
			} else {
				return 'status-ended';    // 已结束
			}
		},
		
		// 获取活动状态文本
		getStatusText(activity) {
			// 根据后端返回的status字段判断状态
			if (activity.status === 0) {
				return '未开始';
			} else if (activity.status === 1) {
				return '报名中';
			} else {
				return '已结束';
			}
		},
		
		// 处理按钮点击
		async handleActionClick() {
			// 判断用户是否登录
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo || !userInfo.id) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
				return;
			}
			
			// 活动未开始或已结束，不可操作
			if (this.activityDetail.status === 0 || this.activityDetail.status === 2) {
				return;
			}
			
			// 如果已经报名，则取消报名
			if (this.hasJoined) {
				this.cancelActivitySignup();
			} else {
				// 否则报名参加
				this.signupActivity();
			}
		},
		
		// 报名活动
		async signupActivity() {
			// 判断用户是否登录
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo || !userInfo.id) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
				return;
			}
			
			uni.showLoading({
				title: '预约中...'
			});
			
			try {
				const res = await signupActivity(this.id);
				console.log('预约结果:', res);
				
				if (res.code === 200) {
					uni.showToast({
						title: res.message || '预约成功',
						icon: 'success'
					});
					
					// 重新加载活动详情和参与人员列表
					await this.loadActivityDetail();
					await this.loadParticipants();
					
					// 如果服务端接口没有返回最新的isSignedUp状态，手动设置为true
					this.hasJoined = true;
					
					// 设置数据变更标记
					this.dataChanged = true;
					
					// 设置全局变量，标记活动列表需要刷新
					getApp().globalData = getApp().globalData || {};
					getApp().globalData.activityListNeedRefresh = true;
				} else {
					// 显示服务端返回的错误信息
					uni.showModal({
						title: '预约失败',
						content: res.message || '预约失败，请稍后重试',
						showCancel: false
					});
				}
			} catch (error) {
				console.error('预约活动失败', error);
				uni.showToast({
					title: '网络异常，请稍后重试',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},
		
		// 取消报名
		async cancelActivitySignup() {
			// 判断用户是否登录
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo || !userInfo.id) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				return;
			}
			
			uni.showModal({
				title: '提示',
				content: '确定要取消预约吗？',
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: '取消中...'
						});
						
						try {
							const result = await cancelSignup(this.id);
							console.log('取消预约结果:', result);
							
							if (result.code === 200) {
								uni.showToast({
									title: result.message || '已取消预约',
									icon: 'success'
								});
								
								// 重新加载活动详情和参与人员列表
								await this.loadActivityDetail();
								await this.loadParticipants();
								
								// 如果服务端接口没有返回最新的isSignedUp状态，手动设置为false
								this.hasJoined = false;
								
								// 设置数据变更标记
								this.dataChanged = true;
								
								// 设置全局变量，标记活动列表需要刷新
								getApp().globalData = getApp().globalData || {};
								getApp().globalData.activityListNeedRefresh = true;
							} else {
								uni.showModal({
									title: '取消失败',
									content: result.message || '取消预约失败，请稍后重试',
									showCancel: false
								});
							}
						} catch (error) {
							console.error('取消预约失败', error);
							uni.showToast({
								title: '网络异常，请稍后重试',
								icon: 'none'
							});
						} finally {
							uni.hideLoading();
						}
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.activity-detail {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 120rpx;
	
	.nav-bar {
		display: flex;
		align-items: center;
		height: 90rpx;
		background-color: #fff;
		padding: 0 30rpx;
		position: relative;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.back-btn {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 10;
			
			&:active {
				opacity: 0.7;
			}
		}
		
		.nav-title {
			position: absolute;
			left: 0;
			right: 0;
			text-align: center;
			font-size: 34rpx;
			font-weight: 500;
			color: #333;
		}
	}
	
	.activity-card {
		background-color: #fff;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		
		.activity-cover {
			position: relative;
			height: 420rpx;
			overflow: hidden;
			
			image {
				width: 100%;
				height: 100%;
				transition: transform 0.8s ease;
				
				&:active {
					transform: scale(1.03);
				}
			}
			
			.status-tag {
				position: absolute;
				top: 20rpx;
				right: 20rpx;
				padding: 8rpx 24rpx;
				border-radius: 30rpx;
				font-size: 26rpx;
				color: #fff;
				font-weight: 500;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
				
				&.status-upcoming {
					background: linear-gradient(to right, #2979ff, #5e9fff);
				}
				
				&.status-ongoing {
					background: linear-gradient(to right, #19be6b, #39e588);
				}
				
				&.status-ended {
					background: linear-gradient(to right, #909399, #c0c4cc);
				}
			}
		}
		
		.activity-info {
			padding: 36rpx;
			
			.activity-title {
				font-size: 38rpx;
				font-weight: bold;
				margin-bottom: 36rpx;
				color: #333;
				line-height: 1.4;
			}
			
			.info-item {
				display: flex;
				align-items: center;
				margin-bottom: 24rpx;
				font-size: 28rpx;
				color: #666;
				
				text {
					margin-left: 12rpx;
				}
			}
			
			.progress-box {
				margin-top: 30rpx;
				
				progress {
					height: 14rpx;
					border-radius: 10rpx;
					overflow: hidden;
				}
			}
		}
	}
	
	.content-card {
		background-color: #fff;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
		border-radius: 2rpx;
		
		.card-title {
			padding: 24rpx 30rpx;
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			border-bottom: 1px solid #f0f0f0;
			position: relative;
			padding-left: 46rpx;
			
			&::before {
				content: '';
				position: absolute;
				left: 30rpx;
				top: 50%;
				transform: translateY(-50%);
				width: 6rpx;
				height: 24rpx;
				background: linear-gradient(to bottom, #2979ff, #5e9fff);
				border-radius: 3rpx;
			}
			
			.title-count {
				font-size: 26rpx;
				color: #999;
				font-weight: normal;
				margin-left: 10rpx;
			}
		}
		
		.activity-content {
			padding: 36rpx;
			font-size: 28rpx;
			color: #333;
			line-height: 1.8;
			word-break: break-word;
			overflow-wrap: break-word;
			word-wrap: break-word;
		}
		
		.participants-list {
			padding: 20rpx 30rpx;
			
			.participant-item {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1px solid #f0f0f0;
				
				&:last-child {
					border-bottom: none;
				}
				
				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					margin-right: 20rpx;
					border: 2rpx solid #f0f0f0;
				}
				
				.nickname {
					flex: 1;
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}
				
				.join-time {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}
	
	.loading-container {
		padding: 40rpx 0;
		display: flex;
		justify-content: center;
	}
	
	.bottom-bar {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 100rpx;
		background-color: #fff;
		padding: 10rpx 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		display: flex;
		align-items: center;
		justify-content: center;
		
		.action-btn {
			width: 90%;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 45rpx;
			text-align: center;
			font-size: 32rpx;
			font-weight: 500;
			color: #fff;
			transition: all 0.3s ease;
			
			&.btn-primary {
				background: linear-gradient(to right, #2979ff, #5e9fff);
				box-shadow: 0 6rpx 16rpx rgba(41, 121, 255, 0.25);
				
				&:active {
					transform: translateY(2rpx);
					box-shadow: 0 3rpx 8rpx rgba(41, 121, 255, 0.25);
				}
			}
			
			&.btn-disabled {
				background-color: #ccc;
				box-shadow: none;
			}
		}
	}
}

/* 富文本内容样式 */
.rich-text-container {
	overflow-x: hidden;
	
	:deep(img), :deep(image) {
		max-width: 100% !important;
		height: auto !important;
		display: block;
		margin: 20rpx auto;
		border-radius: 8rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	:deep(table) {
		width: 100% !important;
		max-width: 100% !important;
		border-collapse: collapse;
		margin: 20rpx 0;
		overflow-x: auto;
		display: block;
		border-radius: 8rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
	}
	
	:deep(td), :deep(th) {
		padding: 12rpx;
		border: 1px solid #eee;
		word-break: break-word;
	}
	
	:deep(th) {
		background-color: #f8f9fa;
		font-weight: 500;
	}
	
	:deep(pre), :deep(code) {
		white-space: pre-wrap;
		word-wrap: break-word;
		background-color: #f8f9fa;
		padding: 16rpx;
		border-radius: 8rpx;
		max-width: 100%;
		overflow-x: auto;
		font-family: Consolas, Monaco, monospace;
		border: 1px solid #eee;
		color: #333;
	}
	
	:deep(iframe), :deep(video) {
		max-width: 100%;
		height: auto;
		border-radius: 8rpx;
		margin: 20rpx 0;
	}
	
	:deep(p) {
		margin: 16rpx 0;
		word-break: break-word;
	}
	
	:deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
		margin: 24rpx 0 16rpx;
		font-weight: 600;
		line-height: 1.4;
	}
	
	:deep(a) {
		color: #2979ff;
		text-decoration: none;
	}
	
	:deep(ul), :deep(ol) {
		padding-left: 40rpx;
		margin: 16rpx 0;
	}
	
	:deep(li) {
		margin: 8rpx 0;
	}
}
</style> 